package com.yjhh.scala

/**
  *
  *
  * Created by hlantian on 2017/11/30.
  */
object HelloPartialFuncation {

  def main(args: Array[String]): Unit = {

    val sample = 1 to 10

    val isEven: PartialFunction[Int, String] = {
      case x if x % 2 == 0 => x + " is even"
    }



    isEven(4)


    val isOdd: PartialFunction[Int, String] = {
      case x if x % 2 == 1 => x + " is odd"
    }

    //val evenNum = sample.collect(isEven orElse isOdd)

    val evenNum = sample.collect{
      case x if x % 2 == 1 => x + " is odd"
      case x if x % 2 == 0 => x + " is even"
    }

    evenNum.foreach(println)

    val map = sample.map(isEven orElse isOdd)
    //map.foreach(println)

    val inc = new PartialFunction[Any, Int] {
      def apply(any: Any) = any.asInstanceOf[Int]+1
      def isDefinedAt(any: Any) = if (any.isInstanceOf[Int]) true else false
    }

    var list = List(1,2,3,4) collect(inc)
    list.foreach(println)

    list = List(1,2,3,4) collect{case i:Int => i+1}
    list.foreach(println)
  }

}
